<template>
  <div class="key-materials-result">
    <div class="result-header">
      <h3>关键材料分析结果</h3>
      <div class="header-actions">
        <el-button type="primary" @click="handleExport" plain>
          <el-icon><Download /></el-icon> 导出数据
        </el-button>
      </div>
    </div>

    <div class="analysis-description">
      <p>本表展示了产品链中的关键节点。连接度是指节点与其他产品/材料的直接连接数量，中介中心性反映了节点的上下游连接情况。数值越高的节点在产业链中扮演着越重要的角色。</p>
      <p v-if="selectedMaterial" class="selected-material-info">
        已选择材料: <span class="selected-material-name">{{ selectedMaterial }}</span>
        <el-button type="success" @click="handleSubstituteAnalysis" class="substitute-button">
          <el-icon><Document /></el-icon> 替代路径分析
        </el-button>
      </p>
      <p v-else class="material-selection-tip">
        点击材料名称可选择进行替代路径分析
      </p>
    </div>

    <el-table
      v-if="tableData.length > 0"
      :data="tableData"
      border
      style="width: 100%"
      :max-height="maxHeight"
      default-sort="{ prop: 'connectionCount', order: 'descending' }"
      @row-click="handleRowClick"
    >
      <el-table-column prop="name" label="材料名称" min-width="150" sortable>
        <template #default="{ row }">
          <el-tooltip
            v-if="row.description"
            :content="row.description"
            placement="top"
            :show-after="500"
          >
            <span class="material-name" :class="{ 'selected': row.name === selectedMaterial }">{{ row.name }}</span>
          </el-tooltip>
          <span v-else class="material-name" :class="{ 'selected': row.name === selectedMaterial }">{{ row.name }}</span>
        </template>
      </el-table-column>
      
      <!-- 连接度 -->
      <el-table-column prop="connectionCount" label="连接度" width="100" sortable align="center">
        <template #default="{ row }">
          <el-tag :type="getValueColor(row.connectionCount, 8, 4)">
            {{ row.connectionCount || '-' }}
          </el-tag>
        </template>
      </el-table-column>
      
      <!-- 中介中心性相关指标 -->
      <el-table-column label="中介中心性" align="center">
        <el-table-column prop="upstreamCount" label="上游" width="90" sortable align="center">
          <template #default="{ row }">
            <el-tag type="info" v-if="row.upstreamCount !== undefined">{{ row.upstreamCount }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="downstreamCount" label="下游" width="90" sortable align="center">
          <template #default="{ row }">
            <el-tag type="info" v-if="row.downstreamCount !== undefined">{{ row.downstreamCount }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>

    <el-empty v-else description="暂无数据" />
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';
import { Download, Goods, Document, DocumentAdd } from '@element-plus/icons-vue';

export default {
  name: 'KeyMaterialsResult',
  components: {
    Download,
    Goods,
    Document,
    DocumentAdd
  },
  props: {
    data: {
      type: Array,
      default: () => []
    },
    maxHeight: {
      type: [String, Number],
      default: '600'
    }
  },
  emits: ['export', 'substitute-analysis'],
  setup(props, { emit }) {
    // 合并所有数据为统一表格
    const tableData = computed(() => {
      return props.data || [];
    });
    
    // 选中的材料
    const selectedMaterial = ref('');
    
    // 下载状态
    const downloadLoading = ref(false);
    
    // 根据数值返回对应的颜色类型
    const getValueColor = (value, highThreshold = 8, mediumThreshold = 4) => {
      if (value === undefined || value === null) return '';
      if (value >= highThreshold) return 'danger';
      if (value >= mediumThreshold) return 'warning';
      return 'info';
    };
    
    const handleExport = () => {
      emit('export', props.data);
    };
    
    // 处理行点击，记录选中的材料
    const handleRowClick = (row) => {
      selectedMaterial.value = row.name;
    };
    
    // 处理替代路径分析
    const handleSubstituteAnalysis = () => {
      if (!selectedMaterial.value) return;
      emit('substitute-analysis', selectedMaterial.value);
    };
    
    // 下载所有材料信息（该功能已被移除，但保留函数定义以防其他地方调用）
    const downloadAllMaterials = () => {
      downloadLoading.value = true;
      try {
        // 创建简单的CSV内容
        const headers = ['材料名称', '连接度', '上游', '下游'];
        const csvContent = [
          headers.join(','),
          ...tableData.value.map(item => [
            item.name,
            item.connectionCount || '',
            item.upstreamCount || '',
            item.downstreamCount || ''
          ].join(','))
        ].join('\n');
        
        // 创建Blob对象
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        
        // 创建下载链接
        const link = document.createElement('a');
        link.setAttribute('href', url);
        link.setAttribute('download', '关键材料列表.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('下载材料清单失败:', error);
      } finally {
        downloadLoading.value = false;
      }
    };

    return {
      tableData,
      selectedMaterial,
      downloadLoading,
      getValueColor,
      handleExport,
      handleRowClick,
      handleSubstituteAnalysis,
      downloadAllMaterials
    };
  }
};
</script>

<style scoped>
.key-materials-result {
  padding: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.result-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.analysis-description {
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.selected-material-info {
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background-color: #ecf5ff;
  border-radius: 4px;
}

.selected-material-name {
  font-weight: bold;
  color: #409EFF;
}

.material-selection-tip {
  margin-top: 12px;
  color: #909399;
  font-style: italic;
}

.substitute-button {
  margin-left: 12px;
}

.material-name {
  cursor: pointer;
  text-decoration: underline dotted;
  text-decoration-thickness: 1px;
  text-underline-offset: 2px;
}

.material-name.selected {
  font-weight: bold;
  color: #409EFF;
  text-decoration: none;
}

:deep(.el-table) {
  margin-bottom: 20px;
}
</style> 